#include "modelitem.h"

ModelItem::ModelItem(QObject *parent) :
    QObject(parent),
    d(new Data())
{
    initialize();
}

ModelItem::ModelItem(const ModelItem &other) :
    QObject(other.parent()),
    d(other.d)
{
    initialize();
}

QString ModelItem::name() const
{
    return d->name;
}

void ModelItem::setName(const QString &name)
{
    if (name == d->name)
    {
        return;
    }

    d->name = name;

    emit sigChanged();

    onRefresh();
}

int ModelItem::type() const
{
    return qMetaTypeId<ModelItem*>();
}

QVariant ModelItem::sortData() const
{
    return name();
}


void ModelItem::setParent(QObject *parent)
{
    QObject::setParent(parent);

    onRefresh();
    initialize();
}

ModelItem *ModelItem::parentItem() const
{
    return qobject_cast<ModelItem*>(parent());
}

const ModelItem *ModelItem::rootItem() const
{
    ModelItem* item = parentItem();
    if (!item)
    {
        return this;
    }

    return item->rootItem();
}

void ModelItem::onRefresh()
{
    if (this == rootItem())
    {
        d->name.clear();
        emit sigRefresh();
    }

    ModelItem* item = parentItem();
    if (!item)
    {
        return;
    }

    if (item == rootItem())
    {
        setObjectName(d->name);
    }
    else
    {
        setObjectName(QString("%1.%2").arg(item->objectName()).arg(d->name));
    }

    emit sigRefresh();
}

void ModelItem::initialize()
{
    const ModelItem* root = rootItem();
    if (this != root)
    {
        connect(this, SIGNAL(sigChanged()), root, SIGNAL(sigChanged()), Qt::UniqueConnection);
    }

    disconnect(this, SLOT(onRefresh()));

    ModelItem* item = parentItem();
    if (!item)
    {
        return;
    }

    connect(item, SIGNAL(sigRefresh()), this, SLOT(onRefresh()), Qt::UniqueConnection);
}

